<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\common\logic;
require_once '../extend/alidb/aliyun-oss-php-sdk-2.3.1/autoload.php';  
use OSS\OssClient;
use OSS\Core\OssException;


/**
 * oss相关逻辑
 * @package app\common\logic
 */
class Osslogic {
    private $accessKeyId        = 'LTAI4G9KPip2LSwWXN7XxcYe';
    private $accessKeySecret    = 'TVsIcAtwpteTVarJe4T1JqbkJD218x';
    //private $accessKeyId        = 'LTAI4FmtZLM3wactLdEi52tP';
    //private $accessKeySecret    = '4TcKFrb5s8ZwfOxHah3x4MxWMCQuA2';
    //private $endpoint_str       = "xiangmu2020.oss-cn-beijing.aliyuncs.com";// Endpoint以杭州为例，其它Region请按实际情况填写。
    private $endpoint           = "http://oss-cn-beijing.aliyuncs.com";// Endpoint以杭州为例，其它Region请按实际情况填写。
    //private $bucket             = 'xiangmu2020';// 存储空间名称
    private $bucket             = 'muxiaopu2020';// 存储空间名称
    private $timeout            = 3600;// 有效期

    /**
     * 下载文件
     * @param object  从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function initialization($object){
        try {
            // true为开启CNAME。CNAME是指将自定义域名绑定到存储空间上。acs:ram::1543585555475602:role/osssts
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, true);
            
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    /**
     * @expectedException \AlibabaCloud\Client\Exception\ServerException
     * @expectedExceptionMessageRegExp /EntityNotExist.Role: The specified Role not exists/
     * @throws ClientException
     * @throws ServerException
     */
    public function testSts(){
        try {
            //构建阿里云client时需要设置AccessKey ID和AccessKey Secret      
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret);
            Sts::v20150401()
            ->assumeRole()
            //指定角色ARN
            ->withRoleArn('acs:ram::1543585555475602:role/osssts')
            //RoleSessionName即临时身份的会话名称，用于区分不同的临时身份
            ->withRoleSessionName('client_name')
            //设置权限策略以进一步限制角色的权限
            //以下权限策略表示拥有所有OSS的只读权限
            ->withPolicy('{
                "Statement":[
                    {
                        "Action":
                    [
                        "oss:Get*",
                        "oss:List*"
                        ],
                        "Effect": "Allow",
                        "Resource": "*"
                    }
                    ],
            "Version": "1"
            }')
            ->connectTimeout(60)
            ->timeout(65)
            ->request();
            
        } catch (OssException $e) {
            return array_out(-9999, 'error', $e->getMessage());
            //print $e->getMessage();
        }
    }

    /**
     * 回去url
     * @param object  从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function getUrl($object, $timeout = 3600){
        try {
            if($this -> objectexists($object)){
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, true);
                $signedUrl = $ossClient->signUrl($this ->bucket, $object, $timeout);
                return array_out(200, 'success', $signedUrl);
            }else{
                return array_out(-1001, 'error', '资源不存在');
            }
            
        } catch (OssException $e) {
            return array_out(-9999, 'error', $e->getMessage());
            //print $e->getMessage();
        }
    }
    
    /**
     * 判断文件是否存在
     * @param object  从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function objectexists($object){
        //if ($this->ossClient) {
            try {
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, true);
                return $ossClient->doesObjectExist($this->bucket, $object);
            } catch (OssException $e) {
                //writelog('oss:deletefile:' . $e->getMessage() . "\n");
                return false;
            }
        //} else {
           // writelog('oss:createBucket:ossClient is null');
        //}
    }

    /**
     * 下载文件
     * @param object  从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function downFile($object){
        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $localfile = "myfile.mp4";
            $options = array(
                    OssClient::OSS_FILE_DOWNLOAD => $localfile
                );
            $content = $ossClient->getObject($this->bucket, $object= '1.mp4', $options);dump($content);
            print("object content: " . $content);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    /**
     * 上传文件
     * @param object  从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function uploadFile($filePath, $object){
        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

            $rel = $ossClient->uploadFile($this->bucket, $object, $filePath);
            if($rel){
                return array_out(200, 'success', $rel);
            }
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

	/**
     * 图片信息
	 * FileSize 	图片大小
	 * Format 		图片类型
	 * ImageHeight 	图片高度
	 * ImageWidth 	图片宽度
     * @param object  从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @author shiqiang
     * @return mixed
     */
    public function infoFile($img_url){
        try {
			$url = explode('?', $img_url);
            $json = file_get_contents($url[0] . '?x-oss-process=image/info');
			if($json){
				$rel = [];
				$array = json_decode($json, true);
			
				$rel['filesize'] 	= $array['FileSize']['value'];
				$rel['format'] 		= $array['Format']['value'];
				$rel['width'] 		= $array['ImageWidth']['value'];
				$rel['height'] 		= $array['ImageHeight']['value'];
				return array_out(200, 'success', $rel);
			}
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

}